<template>
  <div
    class="view-chart"
    :style="{
      width: detail.style.position.w + 'px',
      height: detail.style.position.h + 'px',
    }"
  />
</template>

<script>
import * as echarts from 'echarts'
import { listData } from '@/api/iot/iotDeviceExplainDataApi'
import { getExplain } from '@/api/iot/iotDeviceExplainApi'
import { failureNotice, formatDate, formatExplainType } from '@/util/common'
import { getEnableEval, getFilterRepeat } from '@/util/storage'
import BaseView from '../../../BaseView'

export default {
  extends: BaseView,
  props: {},
  data() {
    return {
      chart: null,
      explain: {},
      filterRepeat: getFilterRepeat(),
      enableEval: getEnableEval()
    }
  },
  watch: {
    detail: {
      deep: true,
      handler() {
        this.chart.resize()
      }
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    onResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    getExplain() {
      getExplain({
        deviceId: this.detail.dataBind.deviceId,
        keyName: this.detail.dataBind.keyName,
        port: this.detail.dataBind.port
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.explain = data
          this.listSearch()
        }
      })
    },
    init() {
      if (!this.chart) {
        this.chart = echarts.init(this.$el)
      }
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 7 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.getExplain()
    },
    formatExplainType(type) {
      return formatExplainType(this, type)
    },
    listSearch() {
      if (this.startDate == null) {
        failureNotice(this, this.$t('start') + this.$t('time'))
        return
      }
      if (this.endDate == null) {
        failureNotice(this, this.$t('end') + this.$t('time'))
        return
      }
      this.listData()
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    formatterSeconds(time) {
      if (time > 3600) {
        return parseInt(time / 3600) + this.$t('hour')
      } else if (time > 60) {
        return parseInt(time / 60) + this.$t('minutes')
      } else {
        return time + this.$t('seconds')
      }
    },
    listData() {
      listData({
        port: this.explain.port,
        deviceId: this.explain.deviceId,
        startTime: Math.round(this.startDate / 1000),
        endTime: Math.round(this.endDate / 1000),
        keyName: this.explain.keyName,
        enableEval: this.enableEval === '1',
        filterRepeat: this.filterRepeat === '1'
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const dy = []
          const dx = []

          if (data.length === 0) {
            dx.push(formatDate(this, this.explain.valueDate))
            dy.push(this.enableEval === '1' ? this.explain.value : this.explain.rawValue)
          } else {
            for (const item of data) {
              dx.push(formatDate(this, item.createdTime))
              dy.push(item.val)
            }
          }

          this.setOptions({
            unit: this.explain.unit,
            classify: this.explain.classify,
            name: this.explain.name,
            type: this.explain.type,
            dataList: dy,
            dateList: dx
          })
        }
      })
    },
    setOptions(explainData) {
      const { dataList, dateList } = explainData
      const option = {
        xAxis: {
          data: dateList,
          boundaryGap: false,
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#909399',
              fontSize: 10
            }
          }
        },
        grid: {
          left: 20,
          right: 35,
          bottom: 10,
          top: 20,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          formatter(params) {
            for (const x in params) {
              return this.$t('date') + ':' + params[x].axisValueLabel + ';' + this.$t('data') + ':' + params[x].value + ' ' + this.explain.unit
            }
          }
        },
        yAxis: {
          axisTick: {
            show: false
          },
          axisLabel: {
            formatter: '{value}' + this.explain.unit
          },
          axisLine: {
            lineStyle: {
              color: '#909399',
              fontSize: 10
            }
          },
          splitLine: {
            show: false
          },
          splitArea: {
            show: false
          }
        },
        series: {
          type: 'line',
          itemStyle: {
            normal: {
              color: '#03c2c2',
              areaStyle: {
                color: '#e8f8f1'
              }
            }
          },
          smooth: true,
          data: dataList,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
          // label: {
          //   show: true,
          //   position: 'bottom', // 位置
          //   color: '#1CD8A8',
          //   fontSize: 10,
          //   distance: 300 // 距离
          // } // 柱子上方的数值
        }
      }
      this.chart.setOption(option)
    }
  }
}
</script>
<style lang="scss">
.view-chart {
  height: 100%;
  width: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
